package com.hanthink.system.service.impl.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.hanthink.common.exception.BaseException;
import com.hanthink.system.domain.pc.EmItemFile;
import com.hanthink.system.domain.pc.EmTaskItem;
import com.hanthink.system.mapper.EmTaskItemMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.constant.Constants;
import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.common.utils.ip.IpUtils;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.equipment.EquipConfirmLog;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.repair.Equip;
import com.hanthink.system.domain.repair.EquipOperLog;
import com.hanthink.system.domain.repair.EquipSelfCheckFileVo;
import com.hanthink.system.domain.repair.EquipSelfCheckVo;
import com.hanthink.system.domain.repair.EquipStandardPic;
import com.hanthink.system.domain.repair.EquipTaskItem;
import com.hanthink.system.domain.repair.Task;
import com.hanthink.system.domain.repair.TaskFile;
import com.hanthink.system.domain.repair.TaskItem;
import com.hanthink.system.domain.repair.TaskSelect;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.SysSerialNumberMapper;
import com.hanthink.system.mapper.task.TaskExecuteMapper;
import com.hanthink.system.service.task.TaskExecuteService;

@Service
public class TaskExecuteServiceImpl implements TaskExecuteService {

	@Autowired
	private TaskExecuteMapper taskExecuteMapper;

	@Autowired
	private SysSerialNumberMapper sysSerialNumberMapper;

	@Autowired
	private EmEquipMapper emEquipMapper;

	@Autowired
	private EmTaskItemMapper emTaskItemMapper;

	@Override
	public Task queryTaskInfo(Equip equip) {
		return taskExecuteMapper.queryTaskInfo(equip);
	}

	@Override
	public TaskItem queryTaskItemUndoInfo(Task task) {
		return taskExecuteMapper.queryTaskItemUndoInfo(task);
	}

	@Override
	public List<EquipTaskItem> queryTaskItemUnCreatedInfo(Equip equip) {
		return taskExecuteMapper.queryTaskItemUnCreatedInfo(equip);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<TaskItem> createTaskWithItem(List<EquipTaskItem> eqTaskItemList, Map<String, Object> map) {
		// 任务项列表
		List<TaskItem> itemList = null;
		// 任务项附件列表
		List<TaskFile> taskFileList = null;
		// 获取序列号
		SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
		String taskCode = SerialNumberUtil.getSerialNumber(BusinessConstants.CHECK_FLAG, serial.getNextValue(),
				serial.getToday());
		// 操作用户
		SysUser sysUser = (SysUser) map.get("user");
		if (CollectionUtils.isNotEmpty(eqTaskItemList)) {
			// 创建Task
			Task task = new Task();
			task.setSiteKey(eqTaskItemList.get(0).getSiteKey());
			task.setTaskCode(taskCode);
			task.setEqKey(eqTaskItemList.get(0).getEqKey());
			task.setTaskType(BusinessConstants.TASK_TYPE_DJ);
			task.setTaskCategory(BusinessConstants.TASK_CAT_SB);
			task.setStatus(BusinessConstants.TASK_STATUS_PREPARE);
			task.setEqStatus(map.get("eqStatus").toString());
			task.setDepartment(eqTaskItemList.get(0).getDepartment());
			task.setExecuter(sysUser.getUserName());
			// 保存Task
			int count = taskExecuteMapper.saveTask(task);
			if (count > 0) {
				itemList = new ArrayList<TaskItem>();
				// 创建TaskItem
				TaskItem item = null;

				// foreach方式插入，解决Insert无法返回主键问题
				for (EquipTaskItem equipTaskItem : eqTaskItemList) {
					item = new TaskItem();
					item.setTaskKey(taskCode);
					item.setSiteKey(equipTaskItem.getSiteKey());
					item.setOrderNum(equipTaskItem.getSortNum());
					item.setItemCode(equipTaskItem.getItemCode());
					item.setItemDesc(equipTaskItem.getItemDesc());
					item.setItemName(equipTaskItem.getItemName());
					item.setItemType(equipTaskItem.getItemType());
					item.setExecuteMeans(equipTaskItem.getExecuteMeans());
					item.setFilePath(equipTaskItem.getFilePath());
					item.setResourceList(new String[0]);
					item.setResourceUrl("");
					taskExecuteMapper.saveTaskItem(item);
					// 保存TaskItem
					itemList.add(item);
				}

				taskFileList = new ArrayList<TaskFile>();
				// 创建TaskItem
				TaskFile taskFile = null;
				// 创建TaskFile
				for (TaskItem taskItem : itemList) {
					taskFile = new TaskFile();
					taskFile.setTaskKey(taskCode);
					taskFile.setTaskItemKey(taskItem.getId());
					taskFile.setSiteKey(taskItem.getSiteKey());
					taskFile.setFileType(taskItem.getExecuteMeans());
					taskFileList.add(taskFile);
				}

				// 保存TaskItemFile
				int res = taskExecuteMapper.saveTaskFile(taskFileList);
				if (res > 0) {
					return itemList;
				} else {
					throw new CustomException("创建设备点检项失败！");
				}
			} else {
				throw new CustomException("创建设备点检任务失败！");
			}
		}
		return null;
	}




	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveOrUpdateTaskItemInfo(List<TaskItem> itemList) {

		// 更新任务项
		int result = taskExecuteMapper.saveSingleTaskItemInfo(itemList.get(0));

		if(result<=0){
			throw new BaseException("保存失败，请重试");
		}

		/**
		// 更新任务子项,只有一个
		for (TaskItem item : itemList) {
			if (item.getSelects() != null && item.getSelects().size() > 0) {
				taskExecuteMapper.updateTaskItemSelect(item.getSelects());
			}
		}
		 */
		// 删除文件记录
		taskExecuteMapper.deleteFileRecordByCode(itemList.get(0));

		List<TaskFile> fileList = new ArrayList<>();
		TaskFile taskFile = null;
		for (TaskItem taskItem : itemList) {
			taskFile = new TaskFile();
			String resourceUrl = "";
			if (ArrayUtils.isNotEmpty(taskItem.getResourceList())) {
				for (String resource : taskItem.getResourceList()) {
					resourceUrl += (resource + ";");
				}
			}

			taskFile.setSiteKey(taskItem.getSiteKey());
			taskFile.setTaskKey(taskItem.getTaskKey());
			taskFile.setTaskItemKey(taskItem.getId());
			taskFile.setFileType(taskItem.getExecuteMeans());
			taskFile.setFilePath(resourceUrl);
			fileList.add(taskFile);
		}
		// 新增文件附件列表
		taskExecuteMapper.saveTaskFile(fileList);
		Task task = new Task();
		task.setExecuter(itemList.get(0).getExecuter());
		task.setTaskCode(itemList.get(0).getTaskKey());
		//如果任务子项只有一项，判断更新任务开始时间
		taskExecuteMapper.updateTaskStatusAndProgress(task);
		// 更新任务单状态
		taskExecuteMapper.updateTaskStatus(task);
		return true;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveOrUpdateTaskItemInfo1(List<TaskItem> itemList) {

		//数据校验
//		if (itemList.get(0).getId()==null|| itemList.get(0).getSiteKey()==null || StringUtils.isEmpty(itemList.get(0).getItemResult())) {
//			throw new BaseException("保存失败，请重试");
//		}

		// 更新任务项
		int result = taskExecuteMapper.saveSingleTaskItemInfo(itemList.get(0));

		if(result<=0){
			throw new BaseException("保存失败，请重试");
		}


		// 更新任务子项,只有一个
		for (TaskItem item : itemList) {
			if (item.getSelects() != null && item.getSelects().size() > 0) {
				taskExecuteMapper.updateTaskItemSelect(item.getSelects());
			}
		}

		// 删除文件记录
		taskExecuteMapper.deleteFileRecordByCode(itemList.get(0));

		List<TaskFile> fileList = new ArrayList<>();
		TaskFile taskFile = null;
		for (TaskItem taskItem : itemList) {
			taskFile = new TaskFile();
			String resourceUrl = "";
			if (ArrayUtils.isNotEmpty(taskItem.getResourceList())) {
				for (String resource : taskItem.getResourceList()) {
					resourceUrl += (resource + ";");
				}
			}

			taskFile.setSiteKey(taskItem.getSiteKey());
			taskFile.setTaskKey(taskItem.getTaskKey());
			taskFile.setTaskItemKey(taskItem.getId());
			taskFile.setFileType(taskItem.getExecuteMeans());
			taskFile.setFilePath(resourceUrl);
			fileList.add(taskFile);
		}

		// 新增文件附件列表
		taskExecuteMapper.saveTaskFile(fileList);


		Task task = new Task();
		task.setExecuter(itemList.get(0).getExecuter());
		task.setTaskCode(itemList.get(0).getTaskKey());
		// 更新任务单状态
		taskExecuteMapper.updateTaskStatusAndProgress(task);
		return true;
	}

	@Override
	public List<TaskItem> queryTaskItemInfo(Equip equip) {
		List<TaskItem> itemList = taskExecuteMapper.queryTaskItemInfo(equip);
		if (CollectionUtils.isNotEmpty(itemList)) {
			boolean activedFlag = false;
			for (TaskItem taskItem : itemList) {
				if (!activedFlag && (taskItem.getItemResult() == null || "".equals(taskItem.getItemResult().trim()))) {
					taskItem.setActived(true);
					activedFlag = true;
				}
				String resourceUrl = taskItem.getResourceUrl();
				if (StringUtils.isNotBlank(resourceUrl)) {
					String[] arr = resourceUrl.split(";");
					taskItem.setResourceList(arr);
				}
				if (ArrayUtils.isEmpty(taskItem.getResourceList())) {
					taskItem.setResourceList(new String[0]);
				}
			}
		}
		return itemList;
	}

	@Override
	public List<EquipStandardPic> queryStandardPicList(Equip equip) {
		return taskExecuteMapper.queryStandardPicList(equip);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveEquipSelfCheckInfo(EquipSelfCheckVo scv, LoginUser loginUser) {
		List<EquipSelfCheckFileVo> resourceList = new ArrayList<EquipSelfCheckFileVo>();
		// 保存自检信息ObjectUtils.isNotEmpty(scv)
		if (scv != null) {
			// 操作用户
			SysUser user = loginUser.getUser();
			// 获取序列号
			SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
			String repairCode = SerialNumberUtil.getSerialNumber(BusinessConstants.SELF_REPAIR_FLAG,
					serial.getNextValue(), serial.getToday());
			scv.setStatus(BusinessConstants.SELF_CHECK_STATE_PREPARE);
			scv.setRepairCode(repairCode);
			scv.setRepairUser(user.getUserName());
			scv.setSiteKey(Long.valueOf(user.getSite()));
			int count = taskExecuteMapper.saveEquipSelfCheckInfo(scv);
			if (count > 0) {
				// 保存自修文件信息
				EquipSelfCheckFileVo resourceVo = null;
				if (ArrayUtils.isNotEmpty(scv.getPicList())) {
					resourceVo = new EquipSelfCheckFileVo();
					String picUrl = "";
					for (String pic : scv.getPicList()) {
						picUrl += (pic + ";");
					}
					resourceVo.setFilePath(picUrl);
					resourceVo.setRequestId(scv.getId());
					resourceVo.setSiteKey(user.getSite());
					resourceVo.setFileType(Constants.RESOURCE_PIC);
					resourceList.add(resourceVo);
				}

				if (ArrayUtils.isNotEmpty(scv.getVideoList())) {
					resourceVo = new EquipSelfCheckFileVo();
					String videoUrl = "";
					for (String video : scv.getVideoList()) {
						videoUrl += (video + ";");
					}
					resourceVo.setFilePath(videoUrl);
					resourceVo.setRequestId(scv.getId());
					resourceVo.setSiteKey(user.getSite());
					resourceVo.setFileType(Constants.RESOURCE_VIDEO);
					resourceList.add(resourceVo);
				}

				if (ArrayUtils.isNotEmpty(scv.getAudioList())) {
					resourceVo = new EquipSelfCheckFileVo();
					String audioUrl = "";
					for (String audio : scv.getAudioList()) {
						audioUrl += (audio + ";");
					}
					resourceVo.setFilePath(audioUrl);
					resourceVo.setRequestId(scv.getId());
					resourceVo.setSiteKey(user.getSite());
					resourceVo.setFileType(Constants.RESOURCE_AUDIO);
					resourceList.add(resourceVo);
				}

				int result = taskExecuteMapper.saveEquipSelfCheckFileInfo(resourceList);
                //					EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
                //					equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_FALSE);
                //					equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
                //					equipRepairMessageVo.setNewsType(BusinessConstants.NEWS_TYPE_REPAIR);
                //					equipRepairMessageVo.setSendUser(user.getUserName());
                //					equipRepairMessageVo.setSiteKey(user.getSite());
                //					// 保存报修推送信息
                //					equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
                return result > 0;
			}
		}
		return false;
	}

	@Override
	public List<Equip> queryEquipList(LoginUser loginUser) {
		List<Equip> equipList = taskExecuteMapper.queryEquipList(loginUser.getUser());
		return equipList;
	}

	@Override
	public boolean updateEquipInfo(Equip equip, LoginUser loginUser) {

		// 操作用户ObjectUtils.isNotEmpty(equip)
		SysUser user = loginUser.getUser();
		if (equip != null) {
			equip.setStatus(equip.getEqStatus().equals("true") ? BusinessConstants.EQUIP_STATE_RUNING
					: BusinessConstants.EQUIP_STATE_STOPED);
			int count = taskExecuteMapper.updateEquipInfo(equip);
			if (count > 0) {
				EquipOperLog equipOperLog = new EquipOperLog();
				equipOperLog.setEqKey(equip.getId());
				equipOperLog.setSiteKey(equip.getSiteKey());
				equipOperLog.setEquipCode(equip.getEquipCode());
				equipOperLog.setOperUser(user.getUserName());
				equipOperLog.setOperIp(IpUtils.getHostIp());
				equipOperLog.setStatus(equip.getStatus());
				// 插入日志
				int result = taskExecuteMapper.saveEquipOperLog(equipOperLog);
                return result > 0;
			}
		}
		return false;
	}

	@Override
	public void updateTaskStatusCloseTask(Task tasklist){
	//	taskExecuteMapper.updateTaskStatusCloseTask(tasklist);
	}

	@Override
	public boolean updateEquipAppointment(Equip equip, LoginUser loginUser) {

		// 操作用户ObjectUtils.isNotEmpty(equip)
		SysUser user = loginUser.getUser();
		if (equip != null) {
			int count = taskExecuteMapper.updateEquipAppointment(equip);
			if (count > 0) {
				EquipOperLog equipOperLog = new EquipOperLog();
				equipOperLog.setEqKey(equip.getId());
				equipOperLog.setSiteKey(equip.getSiteKey());
				equipOperLog.setEquipCode(equip.getEquipCode());
				equipOperLog.setOperUser(user.getUserName());
				equipOperLog.setOperIp(IpUtils.getHostIp());
				equipOperLog.setStatus(equip.getStatus());
				// 插入日志
				int result = taskExecuteMapper.saveEquipOperLog(equipOperLog);
                return result > 0;
			}
		}
		return false;
	}

	@Override
	public List<Task> queryEquipTaskList(Task task) {

		return taskExecuteMapper.queryEquipTaskList(task);
	}

	/**
	 * 根据点检项ID查询点检项子项信息
	 * 
	 * @param task 任务实体
	 */
	@Override
	public List<TaskSelect> queryTaskItemSelect(TaskSelect select) {

		return taskExecuteMapper.queryTaskItemSelect(select);
	}

	@Override
	public int equipmentNoRepaired(Equip equip) {

		// 获取设备id
		EmEquip emEquip = new EmEquip();
		emEquip.setName(equip.getEquipCode());
		List<EmEquip> equips = emEquipMapper.selectEmEquipList(emEquip);
		if (equips.size() == 0) {
			return 0;
		}
		equip.setId(equips.get(0).getId());
		return taskExecuteMapper.equipmentNoRepaired(equip);
	}

	@Override
	public int saveEquipConfirmLog(EquipConfirmLog equipConfirmLog) {

		return taskExecuteMapper.saveEquipConfirmLog(equipConfirmLog);
	}

}
